//
//  NewFeatureViewController.swift
//  XYWeibo
//
//  Created by 常晓璇 on 6/29/15.
//  Copyright © 2015 chang xiaoxuan. All rights reserved.
//

import UIKit
import FFAutoLayout

private let reuseIdentifier = "Cell"

class NewFeatureViewController: UICollectionViewController {

///  界面布局
    let layout = UICollectionViewFlowLayout()
    
    init() {
        super.init(collectionViewLayout: layout)
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Uncomment the following line to preserve selection between presentations
        // self.clearsSelectionOnViewWillAppear = false

        // Register cell classes 注册可重用cell
        self.collectionView!.registerClass(NewFeatureCell.self, forCellWithReuseIdentifier: reuseIdentifier)

        // Do any additional setup after loading the view.
    }

    override func viewWillAppear(animated: Bool) {
        super.viewWillAppear(animated)
        
        // 设置布局
        layout.itemSize = view.bounds.size
        layout.minimumInteritemSpacing = 0
        layout.minimumLineSpacing = 0
        layout.scrollDirection = UICollectionViewScrollDirection.Horizontal
        
        // 设置分页
        collectionView?.pagingEnabled = true
        collectionView?.showsHorizontalScrollIndicator = false
        collectionView?.bounces = false
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        // Get the new view controller using [segue destinationViewController].
        // Pass the selected object to the new view controller.
    }
    */

    // MARK: UICollectionViewDataSource

    let imageCount = 4


    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // #warning Incomplete implementation, return the number of items
        return imageCount
    }

    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(reuseIdentifier, forIndexPath: indexPath) as! NewFeatureCell
        
        // Configure the cell
        cell.imageIndex = indexPath.item
        
        return cell
    }

    // MARK: UICollectionViewDelegate

 
    override func collectionView(collectionView: UICollectionView, didEndDisplayingCell cell: UICollectionViewCell, forItemAtIndexPath indexPath: NSIndexPath) {
        // 获取当前显示的cell
        let path = collectionView.indexPathsForVisibleItems().last!
        
        if path.item == imageCount - 1 {
            // 获取cell 让cell播放动画
            (collectionView.cellForItemAtIndexPath(path) as! NewFeatureCell).showStartButton()
        }
    }

}

class NewFeatureCell: UICollectionViewCell {
///  图像索引
    var imageIndex: Int = 0 {
        didSet {
            iconView.image = UIImage(named: "new_feature_\(imageIndex + 1)")
            
            startButton.hidden = true
        }
    }
    ///  动画显示开始按钮

    func showStartButton() {
        startButton.transform = CGAffineTransformMakeScale(0, 0)
        startButton.hidden = false
        startButton.userInteractionEnabled = false
        
        UIView.animateWithDuration(1.0, delay: 0.0, usingSpringWithDamping: 0.8, initialSpringVelocity: 10, options: UIViewAnimationOptions.CurveEaseIn, animations: { () -> Void in
            self.startButton.transform = CGAffineTransformIdentity
            }, completion: { (_) -> Void in
                print("OK")
                self.startButton.userInteractionEnabled = true
        })
    }
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        addSubview(iconView)
        addSubview(startButton)
        
        startButton.ff_AlignInner(ff_AlignType.BottomCenter, referView: self, size: CGSize(width: 105, height: 36), offset: CGPoint(x: 0, y: -160))
    }

    required init(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    override func layoutSubviews() {
        super.layoutSubviews()
        iconView.frame = self.bounds
    }
    
    /// 图像
    lazy var iconView : UIImageView = {
        return UIImageView()
    }()
    /// 开始按钮
    lazy var startButton: UIButton = {
       let btn = UIButton()
        btn.setTitle("开始体验", forState: UIControlState.Normal)
        
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button"), forState: UIControlState.Normal)
        btn.setBackgroundImage(UIImage(named: "new_feature_finish_button_highlighted"), forState: UIControlState.Highlighted)
        
        btn.addTarget(self, action: "startBtnClick", forControlEvents: UIControlEvents.TouchUpInside)
        
        return btn
    }()
    
    func startBtnClick() {
        NSNotificationCenter.defaultCenter().postNotificationName(XYSwitchRootVCNotification, object: true)
    }
}
